<template>
  <div class="sidebar-container">
    <!-- 头部区域：logo、标题和隐藏按钮 -->
    <div class="flex flex-shrink-0 items-center justify-between p-4 border-b border-gray-200">
      <div class="flex items-center space-x-3">
        <!-- Logo -->
        <div
          class="w-14 h-14 bg-gradient-to-br to-blue-500 rounded-lg flex items-center justify-center"
        >
          <img src="@/assets/imgs/file-preview.png" alt="logo" class="w-full h-full" />
        </div>
        <!-- 标题 -->
        <div>
          <h1 class="text-lg font-semibold text-gray-900">电价政策问答助手</h1>
        </div>
      </div>

      <!-- 隐藏按钮 -->
      <button
        @click="handleHideSidebar"
        class="p-1.5 rounded-md hover:bg-gray-100 transition-colors duration-200"
      >
        <svg class="w-5 h-5 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M15 19l-7-7 7-7"
          />
        </svg>
      </button>
    </div>

    <!-- 新建聊天按钮 -->
    <div v-if="list.length < MAX_CONVERSATION_LENGTH" class="flex flex-shrink-0 p-4 !pb-0">
      <button
        @click="handleNewChat"
        class="group block w-full flex-shrink-0 !justify-start !h-9 text-[#1c64f2] items-center text-sm bg-transparent border border-gray-300 rounded-md px-3 py-2 hover:bg-gray-50 transition-colors duration-200 flex"
      >
        <PencilSquareIcon class="mr-2 h-4 w-4" />
        {{ t('chat.newChat') }}
      </button>
    </div>

    <!-- 对话列表 -->
    <nav class="mt-4 flex-1 space-y-1 bg-white p-4 !pt-0">
      <div
        v-for="item in list"
        :key="item.id"
        :class="[
          'group flex items-center rounded-md px-2 py-2 text-sm font-medium cursor-pointer transition-colors duration-200 relative',
          item.id === currentId
            ? 'bg-primary-50 text-[#1c64f2]'
            : 'text-gray-700 hover:bg-gray-100 hover:text-gray-700'
        ]"
      >
        <!-- 对话内容区域 -->
        <div @click="handleConversationClick(item.id)" class="flex items-center flex-1 min-w-0">
          <component
            :is="
              item.id === currentId
                ? ChatBubbleOvalLeftEllipsisSolidIcon
                : ChatBubbleOvalLeftEllipsisIcon
            "
            :class="[
              'mr-3 h-5 w-5 flex-shrink-0',
              item.id === currentId ? 'text-[#1c64f2]' : 'text-gray-400 group-hover:text-gray-500'
            ]"
            aria-hidden="true"
          />
          <span class="truncate">{{ item.name }}</span>
        </div>

        <!-- 下拉菜单按钮 -->
        <div class="relative">
          <button
            @click.stop="toggleDropdown(item.id)"
            class="opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-gray-200 transition-all duration-200"
            :class="{ 'opacity-100': activeDropdown === item.id }"
          >
            <EllipsisVerticalIcon class="h-4 w-4 text-gray-500" />
          </button>

          <!-- 下拉菜单 -->
          <div
            v-if="activeDropdown === item.id"
            class="absolute right-0 top-8 w-32 bg-white rounded-md shadow-lg border border-gray-200 py-1 z-10"
            @click.stop
          >
            <button
              @click="openRenameModal(item)"
              class="w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-100 flex items-center"
            >
              <PencilIcon class="h-4 w-4 mr-2" />
              重命名
            </button>
            <button
              @click="openDeleteModal(item)"
              class="w-full text-left px-3 py-2 text-sm text-red-600 hover:bg-red-50 flex items-center"
            >
              <TrashIcon class="h-4 w-4 mr-2" />
              删除
            </button>
          </div>
        </div>
      </div>
    </nav>

    <!-- 版权信息 -->
    <div class="flex flex-shrink-0 pr-4 pb-4 pl-4">
      <div class="text-gray-400 font-normal text-xs">
        © {{ copyRight }} {{ new Date().getFullYear() }}
      </div>
    </div>

    <!-- 弹窗组件 -->
    <ConversationModal
      :show-rename-modal="showRenameModal"
      :show-delete-modal="showDeleteModal"
      :conversation-id="selectedConversation?.id || ''"
      :conversation-name="selectedConversation?.name || ''"
      @close-rename="closeRenameModal"
      @close-delete="closeDeleteModal"
      @rename-success="handleRenameSuccess"
      @delete-success="handleDeleteSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'
import {
  ChatBubbleOvalLeftEllipsisIcon,
  PencilSquareIcon,
  EllipsisVerticalIcon,
  PencilIcon,
  TrashIcon
} from '@heroicons/vue/24/outline'
import { ChatBubbleOvalLeftEllipsisIcon as ChatBubbleOvalLeftEllipsisSolidIcon } from '@heroicons/vue/24/solid'
import type { ConversationItem } from '@/types/app'
import ConversationModal from './ConversationModal.vue'
import { useConversationStore } from '@/store/modules/conversation'

const { t } = useI18n()
const conversationStore = useConversationStore()

const MAX_CONVERSATION_LENGTH = 100

interface Props {
  copyRight: string
  currentId: string
  list: ConversationItem[]
}

interface Emits {
  (e: 'current-id-change', id: string): void
  (e: 'toggle-sidebar'): void
}

defineProps<Props>()
const emit = defineEmits<Emits>()

// 下拉菜单状态
const activeDropdown = ref<string | null>(null)
const showRenameModal = ref(false)
const showDeleteModal = ref(false)
const selectedConversation = ref<ConversationItem | null>(null)

const handleNewChat = () => {
  emit('current-id-change', '-1')
}

const handleConversationClick = (id: string) => {
  emit('current-id-change', id)
}

const handleHideSidebar = () => {
  emit('toggle-sidebar')
  // 隐藏时关闭下拉菜单
  closeDropdown()
}

const toggleDropdown = (id: string) => {
  activeDropdown.value = activeDropdown.value === id ? null : id
}

const closeDropdown = () => {
  activeDropdown.value = null
}

const openRenameModal = (conversation: ConversationItem) => {
  selectedConversation.value = conversation
  showRenameModal.value = true
  closeDropdown()
}

const openDeleteModal = (conversation: ConversationItem) => {
  selectedConversation.value = conversation
  showDeleteModal.value = true
  closeDropdown()
}

const closeRenameModal = () => {
  showRenameModal.value = false
  selectedConversation.value = null
}

const closeDeleteModal = () => {
  showDeleteModal.value = false
  selectedConversation.value = null
}

const handleRenameSuccess = (newName: string) => {
  if (selectedConversation.value) {
    // 更新store中的对话名称
    conversationStore.updateConversation(selectedConversation.value.id, { name: newName })
  }
}

const handleDeleteSuccess = () => {
  if (selectedConversation.value) {
    // 从store中移除对话
    conversationStore.removeConversation(selectedConversation.value.id)

    // 如果删除的是当前对话，切换到新建对话
    if (selectedConversation.value.id === conversationStore.currConversationId) {
      emit('current-id-change', '-1')
    }
  }
}

// 点击外部关闭下拉菜单
const handleClickOutside = (event: MouseEvent) => {
  const target = event.target as HTMLElement
  if (!target.closest('.relative')) {
    closeDropdown()
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.sidebar-container {
  width: 300px;
  height: 100%;
  background: white;
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 50;
}

/* 侧边栏导航区域可以滚动 */
.sidebar-container nav {
  overflow-y: auto;
  /* 防止滚动穿透 */
  overscroll-behavior: contain;
  /* iOS Safari优化 */
  -webkit-overflow-scrolling: touch;
  /* 确保可以正确滚动 */
  min-height: 0;
}

@media (min-width: 768px) and (max-width: 1023px) {
  .sidebar-container {
    width: 240px;
  }
}

@media (max-width: 767px) {
  .sidebar-container {
    width: 280px;
  }
}
</style>
